package moe.util;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import moe.config.Configuration;
import moe.entity.Post;

public class UriMappedUtil {
	private static final Map<String, String> URI_Escape = new HashMap<String, String>();

	static {
		URI_Escape.put("\\\\", "%5C");
		URI_Escape.put("/", "%2F");
		URI_Escape.put(":", "%3A");
		URI_Escape.put("\\?", "%3F");
		URI_Escape.put("\\*", "%2A");
		URI_Escape.put("\"", "%22");
		URI_Escape.put("<", "%3C");
		URI_Escape.put(">", "%3E");
		URI_Escape.put("\\|", "%7C");
	}

	public static void resolveUrl(List<Post> list) {
		for (Post post : list) {
			resolveUrl(post);
		}
	}

	public static Post resolveUrl(Post post) {
		long id = post.id;
		String md5 = post.md5;
		String fileUrl = post.fileUrl;
		try {
			fileUrl = URLDecoder.decode(fileUrl, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			// ignore
		}
		String previewUrl = post.previewUrl;
		String ext = fileUrl.substring(fileUrl.lastIndexOf('.'));

		StringBuilder builder = new StringBuilder("/moe.imouto.p");
		if (Configuration.isImoutoCollectPattern()) {
			String fileName = fileUrl.substring(fileUrl.lastIndexOf('/'));
			fileName = yandeToMoe(fileName);
			builder.append(id / 10000 + 1).append("/").append(md5).append(fileName);
		} else {
			builder.append(id / 10000 + 1)
					.append("/moe ")
					.append(id)
					.append(".")
					.append(md5)
					.append(ext);
		}
		post.fileUrl = builder.toString();

		ext = previewUrl.substring(previewUrl.lastIndexOf('.'));
		builder = new StringBuilder("/moe.imouto.preview/");
		builder.append(md5.substring(0, 2))
				.append("/")
				.append(md5.substring(2, 4))
				.append("/")
				.append(md5)
				.append(ext);
		post.previewUrl = builder.toString();

		return post;
	}

	public static String escapeIllegalSystemChar(String uri) {
		if (isWindows()) {
			for (String key : URI_Escape.keySet()) {
				uri = uri.replaceAll(key, URI_Escape.get(key));
			}
		} else {
			uri = uri.replaceAll("/", URI_Escape.get("/"));
		}
		return uri;
	}

	private static boolean isWindows() {
		String osName = System.getProperty("os.name");
		if (osName.contains("Windows")) {
			return true;
		}
		return false;
	}

	public static String yandeToMoe(String fileName) {
		if (fileName.indexOf("yande.re") != -1) {
			fileName = fileName.replaceFirst("yande\\.re", "moe");
		}
		return fileName;
	}
}
